import java.util.*;
import java.util.concurrent.*;

public class ParallelMax {
    public static void main(String[] args) {
        final int N = 10000000;
        Random r = new Random();
        int list[] = new int[N];
        for (int i = 1; i <= N; i++) {
            list[i - 1] = r.nextInt();
        }
        System.out.println(max(list));
    }

    public static int max(int[] list) {
        RecursiveTask<Integer> task = new MaxTask(list, 0, list.length, 0);
        ForkJoinPool pool = new ForkJoinPool();
        return pool.invoke(task);
    }

    private static class MaxTask extends RecursiveTask<Integer> {
        private final static int THRESHOLD = 1000;
        private int[] list;
        private int low;
        private int high;
        private int level;

        public MaxTask(int[] list, int low, int high, int level) {
            this.list = list;
            this.low = low;
            this.high = high;
            this.level = level;
        }

        public Integer compute() {
            for (int i = 1; i <= level; i++) {
                System.out.print("\t");
            }
            System.out.println("Entering compute()");
            if (high - low < THRESHOLD) {
                int max = list[0];
                for (int i = low; i < high; i++) {
                    if (list[i] > max) {
                        max = list[i];
                    }
                }
                return new Integer(max);
            }
            else {
                int mid = (low + high) / 2;
                RecursiveTask<Integer> left = new MaxTask(list, low, mid, level + 1);
                RecursiveTask<Integer> right = new MaxTask(list, mid, high, level + 1);

                left.fork();
                right.fork();
                int leftMax = left.join();
                int rightMax = right.join();
                return new Integer(Math.max(leftMax, rightMax));
            }
        }
    }
}
